/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.common.redis.utils.RedisUtils;
import com.comac.ins.isfd.constant.IsfdMeshModelConstants;
import com.comac.ins.isfd.constant.RedisConstants;
import com.comac.ins.isfd.constant.enums.IsfdMeshModelDefinitionLevelEnum;
import com.comac.ins.isfd.domain.IsfdMeshModelStructureDefinition;
import com.comac.ins.isfd.domain.bo.IsfdMeshModelStructureDefinitionBo;
import com.comac.ins.isfd.domain.bo.query.IsfdMeshModelStructureDefinitionQueryBo;
import com.comac.ins.isfd.domain.vo.IsfdMeshModelAndSectionInfoVo;
import com.comac.ins.isfd.domain.vo.IsfdMeshModelStructureDefinitionTreeNodeVo;
import com.comac.ins.isfd.domain.vo.IsfdMeshModelStructureDefinitionVo;
import com.comac.ins.isfd.mapper.IsfdMeshModelStructureDefinitionMapper;
import com.comac.ins.isfd.service.IIsfdMeshModelStructureDefinitionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 自然网格模型库-构型定义Service业务层处理
 *
 * @author hxloongs
 * @date 2025-01-13
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class IsfdMeshModelStructureDefinitionServiceImpl implements IIsfdMeshModelStructureDefinitionService {
    private final static String[] filterSections = {"S10", "S90", "set", "ht"};

    @Autowired
    private IsfdMeshModelStructureDefinitionMapper baseMapper;

    /**
     * 查询自然网格模型库-构型定义
     *
     * @param id 主键
     * @return 自然网格模型库-构型定义
     */
    @Override
    public IsfdMeshModelStructureDefinitionVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询自然网格模型库-构型定义列表
     *
     * @param bo 查询条件
     * @return 自然网格模型库-构型定义分页列表
     */
    @Override
    public TableDataInfo<IsfdMeshModelStructureDefinitionVo> queryPageList(IsfdMeshModelStructureDefinitionQueryBo bo) {
        LambdaQueryWrapper<IsfdMeshModelStructureDefinition> lqw = buildQueryWrapper(bo);
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(bo.getPageNum());
        pageQuery.setPageSize(bo.getPageSize());
        Page<IsfdMeshModelStructureDefinitionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public List<IsfdMeshModelStructureDefinitionTreeNodeVo> listTree(Function<String, List<String>> modelAndBatchMap, Boolean needPLoad, String sectionName) {
        LambdaQueryWrapper<IsfdMeshModelStructureDefinition> lqw = Wrappers.lambdaQuery();
        lqw.in(StringUtils.isNotBlank(sectionName), IsfdMeshModelStructureDefinition::getLevel, IsfdMeshModelDefinitionLevelEnum.MODEL.getValue(), IsfdMeshModelDefinitionLevelEnum.CHILD_SECTION.getValue())
            .or(StringUtils.isNotBlank(sectionName), subLwq -> subLwq.eq(IsfdMeshModelStructureDefinition::getLevel, IsfdMeshModelDefinitionLevelEnum.SECTION.getValue())
                .like(IsfdMeshModelStructureDefinition::getName, sectionName));
        List<IsfdMeshModelStructureDefinition> isfdMeshModelStructureDefinitions = baseMapper.selectList(lqw);
        if (CollectionUtils.isEmpty(isfdMeshModelStructureDefinitions)) {
            return Collections.emptyList();
        }

        List<IsfdMeshModelStructureDefinition> modelDefList = isfdMeshModelStructureDefinitions.stream().filter(i -> IsfdMeshModelDefinitionLevelEnum.MODEL.getValue().equals(i.getLevel())).toList();
        if (CollectionUtils.isEmpty(modelDefList)) {
            return Collections.emptyList();
        }

        List<IsfdMeshModelStructureDefinition> sectionDefList = isfdMeshModelStructureDefinitions.stream()
            .filter(i -> IsfdMeshModelDefinitionLevelEnum.SECTION.getValue().equals(i.getLevel()))
            .toList();
        Map<Long, List<IsfdMeshModelStructureDefinition>> modelIdSectionGroup = sectionDefList.stream()
            .collect(Collectors.groupingBy(IsfdMeshModelStructureDefinition::getParentId));

        List<IsfdMeshModelStructureDefinition> clildSectionDefList = isfdMeshModelStructureDefinitions.stream()
            .filter(i -> IsfdMeshModelDefinitionLevelEnum.CHILD_SECTION.getValue().equals(i.getLevel()))
            .toList();
        Map<Long, List<IsfdMeshModelStructureDefinition>> sectionIdChildSectionGroup = clildSectionDefList.stream()
            .collect(Collectors.groupingBy(IsfdMeshModelStructureDefinition::getParentId));

        // 定义出所有的node集合，
        List<IsfdMeshModelStructureDefinition> modelList = new ArrayList<>();
        List<IsfdMeshModelStructureDefinition> batchNodeList = new ArrayList<>();
        List<IsfdMeshModelStructureDefinition> sectionList = new ArrayList<>();
        List<IsfdMeshModelStructureDefinition> pLoadList = new ArrayList<>();
        List<IsfdMeshModelStructureDefinition> childSectionList = new ArrayList<>();


        // 保留机型，把批次node挂在机型node下
        for (IsfdMeshModelStructureDefinition modelPo : modelDefList) {
            Long modelPoId = modelPo.getId();
            if (!modelIdSectionGroup.containsKey(modelPoId) && StringUtils.isNotBlank(sectionName)) {
                continue;
            }
            String modelNumber = modelPo.getMark();
            List<String> batchNumberList = modelAndBatchMap.apply(modelNumber);
            if (CollectionUtils.isEmpty(batchNumberList)) {
                continue;
            }
            modelList.add(modelPo);
            for (String batchNumber : batchNumberList) {
                Long batchNodeId = IdUtil.getSnowflakeNextId();
                IsfdMeshModelStructureDefinition batchNode = new IsfdMeshModelStructureDefinition();
                batchNode.setName(batchNumber);
                batchNode.setMark(batchNumber);
                batchNode.setLevel(modelPo.getLevel() + 1);
                batchNode.setParentId(modelPoId);
                batchNode.setTopParentId(modelPoId);
                batchNode.setQueryIndex(modelPo.getQueryIndex() + "::" + batchNumber);
                batchNode.setId(batchNodeId);

                // 如果需要P_load
                if (needPLoad) {
                    IsfdMeshModelStructureDefinition pLoadNode = new IsfdMeshModelStructureDefinition();
                    pLoadNode.setName(IsfdMeshModelConstants.MODEL_MESH_P_LOAD_NAME);
                    pLoadNode.setMark(IsfdMeshModelConstants.MODEL_MESH_P_LOAD);
                    pLoadNode.setLevel(batchNode.getLevel() + 1);
                    pLoadNode.setParentId(batchNodeId);
                    pLoadNode.setTopParentId(modelPoId);
                    pLoadNode.setQueryIndex(batchNode.getQueryIndex() + "::" + IsfdMeshModelConstants.MODEL_MESH_P_LOAD);
                    pLoadNode.setId(IdUtil.getSnowflakeNextId());
                    pLoadList.add(pLoadNode);
                }
                batchNodeList.add(batchNode);

                // 把部段node挂在批次node下
                List<IsfdMeshModelStructureDefinition> modelSectionDefList = modelIdSectionGroup.getOrDefault(modelPoId, Collections.emptyList());
                for (IsfdMeshModelStructureDefinition sectionPo : modelSectionDefList) {
                    IsfdMeshModelStructureDefinition sectionNode = buildPo(sectionPo, batchNode.getId());
                    sectionList.add(sectionNode);

                    // 把子部段node挂在部段node下
                    List<IsfdMeshModelStructureDefinition> innerChildSectionList = sectionIdChildSectionGroup.getOrDefault(sectionPo.getId(), Collections.emptyList());
                    for (IsfdMeshModelStructureDefinition isfdMeshModelStructureDefinition : innerChildSectionList) {
                        IsfdMeshModelStructureDefinition childSectionNode = buildPo(isfdMeshModelStructureDefinition, sectionNode.getId());
                        childSectionList.add(childSectionNode);
                    }
                }
            }
        }
        // 把所有数据加入list
        List<IsfdMeshModelStructureDefinition> resultList = new ArrayList<>(modelList);
        resultList.addAll(batchNodeList);
        resultList.addAll(sectionList);
        if (CollectionUtils.isNotEmpty(childSectionList)) {
            // 去重 根据id和parentId
            Map<List<Object>, IsfdMeshModelStructureDefinition> uniqueMap = childSectionList.stream()
                .collect(Collectors.toMap(
                    def -> Arrays.asList(def.getId(), def.getParentId()),
                    Function.identity(),
                    (existing, replacement) -> existing
                ));
            resultList.addAll(new ArrayList<>(uniqueMap.values()));
        }
        if (CollectionUtils.isNotEmpty(pLoadList)) {
            resultList.addAll(pLoadList);
        }

        //最大等级
        Integer maxLevel = resultList.stream()
            .map(IsfdMeshModelStructureDefinition::getLevel)
            .max(Integer::compareTo)
            .orElse(null);
        //递归处理结构树
        if (Objects.isNull(maxLevel)) {
            return Collections.emptyList();
        }

        // 组成树
        List<IsfdMeshModelStructureDefinitionTreeNodeVo> treeVo = new ArrayList<>();
        resultList.forEach(isfdMeshModelStructureDefinition -> {
            if (isfdMeshModelStructureDefinition.getParentId() == 0) {
                IsfdMeshModelStructureDefinitionTreeNodeVo nodeVo = new IsfdMeshModelStructureDefinitionTreeNodeVo();
                BeanUtil.copyProperties(isfdMeshModelStructureDefinition, nodeVo);
                treeVo.add(nodeVo);
            }
        });
        this.handler(treeVo, resultList, 2, maxLevel);
        return treeVo;
    }


    private IsfdMeshModelStructureDefinition buildPo(IsfdMeshModelStructureDefinition po, Long parentId) {
        IsfdMeshModelStructureDefinition childSectionNode = new IsfdMeshModelStructureDefinition();
        childSectionNode.setName(po.getName());
        childSectionNode.setMark(po.getMark());
        childSectionNode.setLevel(po.getLevel() + 1);
        childSectionNode.setParentId(parentId);
        childSectionNode.setTopParentId(po.getTopParentId());
        childSectionNode.setQueryIndex(po.getQueryIndex());
        childSectionNode.setId(po.getId());
        return childSectionNode;
    }

    @Override
    public List<IsfdMeshModelStructureDefinitionTreeNodeVo> listTree(String modelNumber, String batchNumber, Boolean needPLoad) {
        // 找出指定的机型
        IsfdMeshModelStructureDefinitionVo modelVo = this.queryOneByQueryIndex(modelNumber, null, null);
        List<IsfdMeshModelStructureDefinition> isfdMeshModelStructureDefinitions = baseMapper.selectList(
            new LambdaQueryWrapper<IsfdMeshModelStructureDefinition>().eq(IsfdMeshModelStructureDefinition::getTopParentId, modelVo.getId()));

        // 如果批次不为空
        if (StringUtils.isNotBlank(batchNumber)) {
            // 定义出所有的批次node，并把批次节点挂在机型node下
            Map<Long, IsfdMeshModelStructureDefinition> batchNodeMap = new HashMap<>();
            List<IsfdMeshModelStructureDefinition> pLoadList = new ArrayList<>();
            for (IsfdMeshModelStructureDefinition isfdMeshModelStructureDefinition : isfdMeshModelStructureDefinitions) {
                if (isfdMeshModelStructureDefinition.getLevel().equals(IsfdMeshModelDefinitionLevelEnum.MODEL.getValue())) {
                    Long modelPoId = isfdMeshModelStructureDefinition.getId();
                    Long batchNodeId = IdUtil.getSnowflakeNextId();
                    IsfdMeshModelStructureDefinition batchNode = new IsfdMeshModelStructureDefinition();
                    batchNode.setName(batchNumber);
                    batchNode.setMark(batchNumber);
                    batchNode.setLevel(isfdMeshModelStructureDefinition.getLevel() + 1);
                    batchNode.setParentId(modelPoId);
                    batchNode.setTopParentId(modelPoId);
                    batchNode.setQueryIndex(isfdMeshModelStructureDefinition.getQueryIndex() + "::" + batchNumber);
                    batchNode.setId(batchNodeId);

                    if (needPLoad) {
                        IsfdMeshModelStructureDefinition pLoadNode = new IsfdMeshModelStructureDefinition();
                        pLoadNode.setName(IsfdMeshModelConstants.MODEL_MESH_P_LOAD_NAME);
                        pLoadNode.setMark(IsfdMeshModelConstants.MODEL_MESH_P_LOAD);
                        pLoadNode.setLevel(batchNode.getLevel() + 1);
                        pLoadNode.setParentId(batchNodeId);
                        pLoadNode.setTopParentId(modelPoId);
                        pLoadNode.setQueryIndex(batchNode.getQueryIndex() + "::" + IsfdMeshModelConstants.MODEL_MESH_P_LOAD);
                        pLoadNode.setId(IdUtil.getSnowflakeNextId());
                        pLoadList.add(pLoadNode);
                    }
                    batchNodeMap.put(modelPoId, batchNode);
                }
            }

            // 部段节点全部挂到批次node下，并把批次之后的level + 1
            for (IsfdMeshModelStructureDefinition isfdMeshModelStructureDefinition : isfdMeshModelStructureDefinitions) {
                if (isfdMeshModelStructureDefinition.getLevel().equals(IsfdMeshModelDefinitionLevelEnum.SECTION.getValue())) {
                    Long parentId = isfdMeshModelStructureDefinition.getParentId();
                    IsfdMeshModelStructureDefinition batchNode = batchNodeMap.get(parentId);
                    if (batchNode != null) {
                        isfdMeshModelStructureDefinition.setParentId(batchNode.getId());
                    }
                }
                isfdMeshModelStructureDefinition.setLevel(isfdMeshModelStructureDefinition.getLevel() + 1);
            }

            // 把新的批次和P_load加入列表
            isfdMeshModelStructureDefinitions.addAll(batchNodeMap.values());
            if (CollectionUtils.isNotEmpty(pLoadList)) {
                isfdMeshModelStructureDefinitions.addAll(pLoadList);
            }
        }

        List<IsfdMeshModelStructureDefinitionTreeNodeVo> treeVo = new ArrayList<>();
        isfdMeshModelStructureDefinitions.forEach(isfdMeshModelStructureDefinition -> {
            if (isfdMeshModelStructureDefinition.getParentId() == 0) {
                IsfdMeshModelStructureDefinitionTreeNodeVo nodeVo = new IsfdMeshModelStructureDefinitionTreeNodeVo();
                BeanUtil.copyProperties(isfdMeshModelStructureDefinition, nodeVo);
                treeVo.add(nodeVo);
            }
        });
        //最大等级
        Integer maxLevel = isfdMeshModelStructureDefinitions.stream().max(Comparator.comparingInt(IsfdMeshModelStructureDefinition::getLevel)).get().getLevel();
        //递归处理结构树
        this.handler(treeVo, isfdMeshModelStructureDefinitions, 2, maxLevel);
        return treeVo;
    }


    @Override
    public List<IsfdMeshModelStructureDefinitionTreeNodeVo> listTree() {
        List<IsfdMeshModelStructureDefinition> isfdMeshModelStructureDefinitions = baseMapper.selectList();

        List<IsfdMeshModelStructureDefinitionTreeNodeVo> treeVo = new ArrayList<>();

        if (isfdMeshModelStructureDefinitions == null || isfdMeshModelStructureDefinitions.isEmpty()) {
            return treeVo; // 空列表，直接返回
        }

        isfdMeshModelStructureDefinitions.forEach(isfdMeshModelStructureDefinition -> {
            if (isfdMeshModelStructureDefinition.getParentId() == 0) {
                IsfdMeshModelStructureDefinitionTreeNodeVo nodeVo = new IsfdMeshModelStructureDefinitionTreeNodeVo();
                BeanUtil.copyProperties(isfdMeshModelStructureDefinition, nodeVo);
                treeVo.add(nodeVo);
            }
        });
        //最大等级
        Integer maxLevel = isfdMeshModelStructureDefinitions.stream().max(Comparator.comparingInt(IsfdMeshModelStructureDefinition::getLevel)).get().getLevel();
        //递归处理结构树
        this.handler(treeVo, isfdMeshModelStructureDefinitions, 2, maxLevel);
        return treeVo;
    }

    public void handler(List<IsfdMeshModelStructureDefinitionTreeNodeVo> treeVo,
                        List<IsfdMeshModelStructureDefinition> isfdMeshModelStructureDefinitions,
                        Integer level,
                        Integer maxLevel) {
        isfdMeshModelStructureDefinitions.forEach(isfdMeshModelStructureDefinition -> {
            treeVo.forEach(rootTree -> {
                if (rootTree.getId().equals(isfdMeshModelStructureDefinition.getParentId())) {
                    IsfdMeshModelStructureDefinitionTreeNodeVo nodeVo = new IsfdMeshModelStructureDefinitionTreeNodeVo();
                    BeanUtil.copyProperties(isfdMeshModelStructureDefinition, nodeVo);
                    if (rootTree.getChildren() == null) {
                        rootTree.setChildren(new ArrayList<>());
                    }
                    rootTree.getChildren().add(nodeVo);
                }
            });
        });
        treeVo.forEach(item -> {
            if (Objects.nonNull(item.getChildren()) && level < maxLevel) {
                this.handler(item.getChildren(), isfdMeshModelStructureDefinitions, level + 1, maxLevel);
            }
        });
    }

    private LambdaQueryWrapper<IsfdMeshModelStructureDefinition> buildQueryWrapper(IsfdMeshModelStructureDefinitionQueryBo bo) {
        LambdaQueryWrapper<IsfdMeshModelStructureDefinition> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getParentId() != null, IsfdMeshModelStructureDefinition::getParentId, bo.getParentId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), IsfdMeshModelStructureDefinition::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getMark()), IsfdMeshModelStructureDefinition::getMark, bo.getMark());
        lqw.eq(bo.getLevel() != null, IsfdMeshModelStructureDefinition::getLevel, bo.getLevel());
        lqw.eq(StringUtils.isNotBlank(bo.getQueryIndex()), IsfdMeshModelStructureDefinition::getQueryIndex, bo.getQueryIndex());
        if (bo.getFilterSection() != null && bo.getFilterSection()) {
            lqw.notIn(IsfdMeshModelStructureDefinition::getMark, Arrays.asList(filterSections));
        }
        return lqw;
    }

    /**
     * 新增自然网格模型库-构型定义
     *
     * @param bo 自然网格模型库-构型定义
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(IsfdMeshModelStructureDefinitionBo bo) {
        IsfdMeshModelStructureDefinition add = MapstructUtils.convert(bo, IsfdMeshModelStructureDefinition.class);
        QueryWrapper<IsfdMeshModelStructureDefinition> qr = new QueryWrapper<>();
        qr.eq("mark", bo.getMark());
        qr.eq("parent_id", bo.getParentId());
        IsfdMeshModelStructureDefinition node = baseMapper.selectOne(qr);
        if (bo.getMark().contains(":")) {
            throw new BaseException("节点标识：“" + bo.getMark() + "”不能包含特殊字符”:“");
        }
        if (node != null) {
            throw new BaseException("节点标识：“" + bo.getMark() + "”已存在");
        }

//        QueryWrapper<IsfdMeshModelStructureDefinition> qrForName = new QueryWrapper<>();
//        qrForName.eq("name", bo.getName());
//        qrForName.eq("parent_id", bo.getParentId());
//        IsfdMeshModelStructureDefinition nodeForName = baseMapper.selectOne(qrForName);
//        if (nodeForName != null) {
//            throw new BaseException("相同节点下，节点名称：“" + bo.getName() + "”已存在，不可重名");
//        }

        String queryIndex = null;
        if (bo.getParentId() != 0) {
            IsfdMeshModelStructureDefinition parentPo = baseMapper.selectById(bo.getParentId());
            queryIndex = parentPo.getQueryIndex() + "::" + bo.getMark();
            add.setQueryIndex(queryIndex);
            add.setTopParentId(parentPo.getTopParentId());
            baseMapper.insert(add);
            return Boolean.TRUE;
        } else {
            queryIndex = bo.getMark();
            add.setQueryIndex(queryIndex);
            baseMapper.insert(add);
            Long id = add.getId();
            add.setTopParentId(id);
            baseMapper.updateById(add);
            return Boolean.TRUE;
        }
    }

    /**
     * 修改自然网格模型库-构型定义
     *
     * @param bo 自然网格模型库-构型定义
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(IsfdMeshModelStructureDefinitionBo bo) {
        IsfdMeshModelStructureDefinition update = MapstructUtils.convert(bo, IsfdMeshModelStructureDefinition.class);

//        QueryWrapper<IsfdMeshModelStructureDefinition> qrForName = new QueryWrapper<>();
//        qrForName.eq("name", bo.getName());
//        qrForName.eq("parent_id", bo.getParentId());
//        IsfdMeshModelStructureDefinition nodeForName = baseMapper.selectOne(qrForName);
//        if (nodeForName != null && !nodeForName.getId().equals(update.getId())) {
//            throw new BaseException("相同节点下，节点名称：“" + bo.getName() + "”已存在，不可重名");
//        }

        baseMapper.updateById(update);

        //删除redis中的数据
        IsfdMeshModelStructureDefinition isfdMeshModelStructureDefinition = baseMapper.selectById(update.getId());
        if (ObjectUtils.isNotEmpty(isfdMeshModelStructureDefinition)) {
            String redisKey = RedisConstants.ISFD_MESH_MODEL_DEFINITION_TREE_QUERY_INDEX + isfdMeshModelStructureDefinition.getQueryIndex().replaceAll("::", ":");
            RedisUtils.deleteObject(redisKey);
        }
        return Boolean.TRUE;
    }

    /**
     * 删除自然网格模型库-构型定义信息
     */
    @Override
    public Boolean deleteWithValidByIds(Long id) {
        String redisPrefix = RedisConstants.ISFD_MESH_MODEL_DEFINITION_TREE_QUERY_INDEX;
        List<IsfdMeshModelStructureDefinition> allTree = new ArrayList<>();
        ArrayList<String> queryIndexList = new ArrayList<>();
        IsfdMeshModelStructureDefinition node = baseMapper.selectById(id);
        if (node == null) {
            throw new BaseException("选择的构型定义不存在，请确认后重试！");
        }
        allTree.add(node);
        queryIndexList.add(redisPrefix + node.getQueryIndex().replaceAll("::", ":"));
        if (node.getLevel().equals(IsfdMeshModelDefinitionLevelEnum.MODEL.getValue())) {
            // 部段
            QueryWrapper<IsfdMeshModelStructureDefinition> qrChildren = new QueryWrapper<>();
            qrChildren.eq("parent_id", node.getId());
            List<IsfdMeshModelStructureDefinition> sectionNodes = baseMapper.selectList(qrChildren);
            for (IsfdMeshModelStructureDefinition batchVo : sectionNodes) {
                // 子部段
                QueryWrapper<IsfdMeshModelStructureDefinition> qrBatch = new QueryWrapper<>();
                qrBatch.eq("parent_id", batchVo.getId());
                List<IsfdMeshModelStructureDefinition> childSectionNodes = baseMapper.selectList(qrBatch);
                childSectionNodes.forEach(childNode -> {
                    allTree.add(childNode);
                    queryIndexList.add(redisPrefix + childNode.getQueryIndex().replaceAll("::", ":"));
                });
            }
            sectionNodes.forEach(childNode -> {
                allTree.add(childNode);
                queryIndexList.add(redisPrefix + childNode.getQueryIndex().replaceAll("::", ":"));
            });
        } else if (node.getLevel().equals(IsfdMeshModelDefinitionLevelEnum.SECTION.getValue())) {
            QueryWrapper<IsfdMeshModelStructureDefinition> qrChildren = new QueryWrapper<>();
            qrChildren.eq("parent_id", node.getId());
            List<IsfdMeshModelStructureDefinition> childSectionNodes = baseMapper.selectList(qrChildren);
            childSectionNodes.forEach(childNode -> {
                allTree.add(childNode);
                queryIndexList.add(redisPrefix + childNode.getQueryIndex().replaceAll("::", ":"));
            });
        }

        List<Long> allIds = allTree.stream().map(IsfdMeshModelStructureDefinition::getId).collect(Collectors.toList());
        baseMapper.deleteBatchIds(allIds);
        //删除redis中的数据
        RedisUtils.deleteObject(queryIndexList);
        return Boolean.TRUE;
    }


    @Override
    public IsfdMeshModelStructureDefinitionVo queryOneByQueryIndex(String modelNumber,
                                                                   String sectionNumber,
                                                                   String childSectionNumber) {
        String queryIndex = null;
        String redisKey = null;
        if (StringUtils.isBlank(modelNumber)) {
            throw new BaseException("机型编码不能为空。");
        }
        queryIndex = modelNumber;
        redisKey = RedisConstants.ISFD_MESH_MODEL_DEFINITION_TREE_QUERY_INDEX + modelNumber;
        if (StringUtils.isNotBlank(sectionNumber)) {
            queryIndex = queryIndex + "::" + sectionNumber;
            redisKey = redisKey + ":" + sectionNumber;
        }
        if (StringUtils.isNotBlank(childSectionNumber)) {
            queryIndex = queryIndex + "::" + childSectionNumber;
            redisKey = redisKey + ":" + childSectionNumber;
        }
        // 两次try catch 的目的是不让redis报错不影响流程
        try {
            IsfdMeshModelStructureDefinitionVo treeVo = RedisUtils.getCacheObject(redisKey);
            if (treeVo != null) {
                return treeVo;
            }
        } catch (Exception e) {
            log.error("redis异常", e);
        }

        // 从db拿
        IsfdMeshModelStructureDefinitionVo treeVoFromDB = baseMapper.selectVoOne(new LambdaQueryWrapper<IsfdMeshModelStructureDefinition>()
            .eq(IsfdMeshModelStructureDefinition::getQueryIndex, queryIndex));

        if (treeVoFromDB == null) {
            return null;
        }

        try {
            // 放入redis
            RedisUtils.setCacheObject(redisKey, treeVoFromDB, Duration.ofDays(RedisConstants.ISFD_MESH_MODEL_DEFINITION_TREE_QUERY_INDEX_EXPIRATION_DAY));
        } catch (Exception e) {
            log.error("redis异常", e);
        }

        return treeVoFromDB;
    }

    @Override
    public List<IsfdMeshModelStructureDefinitionVo> getAllSectionNames(Boolean filterSection) {
        LambdaQueryWrapper<IsfdMeshModelStructureDefinition> lqw = new LambdaQueryWrapper<IsfdMeshModelStructureDefinition>()
            .eq(IsfdMeshModelStructureDefinition::getLevel, 2);
        if (filterSection != null && filterSection) {
            lqw.notIn(IsfdMeshModelStructureDefinition::getMark, Arrays.asList(filterSections));
        }
        List<IsfdMeshModelStructureDefinitionVo> allSections = baseMapper.selectVoList(lqw);
        if (CollectionUtils.isEmpty(allSections)) {
            return new ArrayList<>();
        }
        return allSections;
    }

    @Override
    public List<IsfdMeshModelStructureDefinitionVo> getAllModelNames() {
        LambdaQueryWrapper<IsfdMeshModelStructureDefinition> lqw = new LambdaQueryWrapper<IsfdMeshModelStructureDefinition>()
            .eq(IsfdMeshModelStructureDefinition::getLevel, 1);
        List<IsfdMeshModelStructureDefinitionVo> allSections = baseMapper.selectVoList(lqw);
        if (CollectionUtils.isEmpty(allSections)) {
            return new ArrayList<>();
        }
        return allSections;
    }

    @Override
    public IsfdMeshModelStructureDefinitionVo getOrCreate(String modelNumber,
                                                          String sectionNumber,
                                                          String childSectionNumber) {
        // 1. 尝试获取已有记录
        IsfdMeshModelStructureDefinitionVo existingVo = queryOneByQueryIndex(modelNumber, sectionNumber, childSectionNumber);
        if (existingVo != null) {
            return existingVo;
        }

        // 2. 构造 queryIndex
        String queryIndex = modelNumber;
        if (StringUtils.isNotBlank(sectionNumber)) {
            queryIndex += "::" + sectionNumber;
        }
        if (StringUtils.isNotBlank(childSectionNumber)) {
            queryIndex += "::" + childSectionNumber;
        }

        // 3. 构建新实体
        IsfdMeshModelStructureDefinition newEntity = new IsfdMeshModelStructureDefinition();
        newEntity.setName(childSectionNumber != null ? childSectionNumber
            : sectionNumber != null ? sectionNumber : modelNumber);
        newEntity.setMark(""); // 根据业务需要设置
        newEntity.setLevel(childSectionNumber != null ? 3
            : sectionNumber != null ? 2 : 1);
        newEntity.setQueryIndex(queryIndex);

        // 4. 设置 parentId 和 topParentId
        if (childSectionNumber != null) {
            // 子部段 -> 父节点是部段
            IsfdMeshModelStructureDefinitionVo parentVo = queryOneByQueryIndex(modelNumber, sectionNumber, null);
            if (parentVo != null) {
                newEntity.setParentId(parentVo.getId());
                newEntity.setTopParentId(parentVo.getTopParentId() != null ? parentVo.getTopParentId() : parentVo.getId());
            }
        } else if (sectionNumber != null) {
            // 部段 -> 父节点是机型
            IsfdMeshModelStructureDefinitionVo parentVo = queryOneByQueryIndex(modelNumber, null, null);
            if (parentVo != null) {
                newEntity.setParentId(parentVo.getId());
                newEntity.setTopParentId(parentVo.getId());
            }
        } // 机型节点 parentId/topParentId 默认 null

        // 5. 插入数据库
        baseMapper.insert(newEntity);

        // 6. 转换为 VO
        IsfdMeshModelStructureDefinitionVo vo = MapstructUtils.convert(newEntity, IsfdMeshModelStructureDefinitionVo.class);

        // 7. 更新 Redis
        String redisKey = RedisConstants.ISFD_MESH_MODEL_DEFINITION_TREE_QUERY_INDEX + modelNumber;
        if (StringUtils.isNotBlank(sectionNumber)) {
            redisKey += ":" + sectionNumber;
        }
        if (StringUtils.isNotBlank(childSectionNumber)) {
            redisKey += ":" + childSectionNumber;
        }
        try {
            RedisUtils.setCacheObject(redisKey, vo,
                Duration.ofDays(RedisConstants.ISFD_MESH_MODEL_DEFINITION_TREE_QUERY_INDEX_EXPIRATION_DAY));
        } catch (Exception e) {
            log.error("redis异常", e);
        }

        return vo;
    }



    @Override
    public List<IsfdMeshModelAndSectionInfoVo> getModelAndSectionInfoBySectionName(String sectionNames) {
        String[] sectionNameArray = sectionNames.split(",");
        List<IsfdMeshModelStructureDefinition> sections = baseMapper.selectList(new LambdaQueryWrapper<IsfdMeshModelStructureDefinition>()
                .eq(IsfdMeshModelStructureDefinition::getLevel, 2)
                .in(IsfdMeshModelStructureDefinition::getName, Arrays.asList(sectionNameArray)));
        if (CollectionUtils.isEmpty(sections)) {
            return new ArrayList<>();
        }
        List<IsfdMeshModelAndSectionInfoVo> result = new ArrayList<>();
        Set<String> modelNumbers = new HashSet<>();
        for (IsfdMeshModelStructureDefinition po : sections) {
            IsfdMeshModelAndSectionInfoVo infoVo = new IsfdMeshModelAndSectionInfoVo();
            Long topParentId = po.getTopParentId();
            IsfdMeshModelStructureDefinition model = baseMapper.selectById(topParentId);
            if(modelNumbers.contains(model.getMark())){
                continue;
            }
            modelNumbers.add(model.getMark());
            infoVo.setModelNumber(model.getMark());
            infoVo.setModelName(model.getName());
            infoVo.setSectionNumber(po.getMark());
            infoVo.setSectionName(po.getName());
            result.add(infoVo);
        }
        return result;
    }
}
